package com.zmx.doctor.fragment.registration_list;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.BooksRecommendedAdapter;
import com.zmx.doctor.adapter.RegistrationListAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.RegistrationList;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.CustomToast;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UntreatedFragment extends Fragment {

    private RecyclerView reView;
    private SmartRefreshLayout refreshLayout;
    private RegistrationListAdapter adapter;
    private List<RegistrationList> lists;
    private View mEmptyLayout;
    Integer pos=0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_untreated, container, false);

        mEmptyLayout = view.findViewById(R.id.empty);
        reView = view.findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(UntreatedFragment.this.getActivity()));
        adapter = new RegistrationListAdapter(UntreatedFragment.this.getActivity());
        reView.setAdapter(adapter);
        lists = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Log.e("点击了","点击了");

                pos = listPosition;
                AlertDialog.Builder builder=new AlertDialog.Builder(UntreatedFragment.this.getContext());
                builder.setTitle("提示：");
                builder.setMessage("是否设置为已就诊？");

                //设置确定按钮
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取图片某布局
                        setRegister(lists.get(listPosition).getId()+"");
                    }
                });
                //设置取消按钮
                builder.setPositiveButton("取消",null);
                //显示提示框
                builder.show();

            }
        });

        // 开启自动加载功能
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            getData();
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> {

            handler.sendEmptyMessage(3);

        });

        //触发自动刷新
        refreshLayout.autoRefresh();
        return view;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:
                    lists.clear();
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if(object.getInt("code") == 1){

                            JSONArray array = object.getJSONArray("data");
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                JSONObject jsonObject = array.getJSONObject(i);
                                RegistrationList taskReward = gson.fromJson(jsonObject.toString(), RegistrationList.class);
                                lists.add(taskReward);

                            }

                            adapter.setListAndNotifyDataSetChanged(lists);//就是设置list然后刷新
                        }

                        refreshLayout.finishRefresh(true);
                        if (lists.size() > 0) {
                            mEmptyLayout.setVisibility(View.GONE);
                        } else {
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        CustomToast.getInstance().showToastCustom(UntreatedFragment.this.getContext(), object.getString("msg"), Gravity.BOTTOM);

                        if(object.getInt("code") == 1){

                            lists.remove(lists.get(pos));
                            adapter.notifyItemRemoved(pos);
                            adapter.notifyItemRangeRemoved(pos, lists.size());

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

            }

        }
    };

    /**
     * 获取所有提问
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add("10");
        ls.add("1");
        ls.add("0");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getRegister");
        params.put("data[status]", "0");
        params.put("data[row]", "1");
        params.put("data[number]", "10");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();

        requestparams.append(MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();
    }

    public void setRegister(String register_id) {

        List<String> ls = new ArrayList<>();
        ls.add(register_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "setRegister");
        params.put("data[register_id]", register_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.Register/entry", params, handler, 2, 404);

    }

}
